package com.forezp.zullsimple.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 自定义filter
 * @Author: yudashuai
 * @Date: 2021/12/30
 * @Version: V1.0
 */
@Component
public class MyFilter extends ZuulFilter {

    /**
     *     filterType：返回一个字符串代表过滤器的类型，在zuul中定义了四种不同生命周期的过滤器类型，具体如下：
     *     pre：路由之前
     *     routing：路由之时
     *     post： 路由之后
     *     error：发送错误调用
     *
     *     常量类 FilterConstants;
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /*过滤的顺序*/
    @Override
    public int filterOrder() {
        return 0;
    }

    /*这里可以写逻辑判断，是否要过滤，本文true,永远过滤。*/
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器的具体逻辑。可用很复杂，包括查sql，nosql去判断该请求到底有没有权限访问。
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        Object accessToken = request.getParameter("token");
        if(accessToken == null) {
            ctx.setSendZuulResponse(false);//过滤该请求，不对其进行路由
            ctx.setResponseStatusCode(401);//返回错误码
            try {
                ctx.getResponse().getWriter().write("token is empty");
            }catch (Exception e){}

        }
        return null;
    }
}
